﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Common;
using Basic.Model.Entity;
using Basic.Model.EntityManager;

namespace Basic.Business
{
    public class AdminAdmin
    {
        #region 添加一个Admin用户
        public static void AddAdmin(string adminName, string adminPass,int adminGroupId)
        {
            ISession session = null;
            ITransaction trans = null;
            Admin admin = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                //冲突处理
                Collision collision = new Collision();
                collision.itemKey="deleteAdminGroup_"+adminGroupId.ToString();
                CollisionManager.AddItem(session, collision);
                
                if (AdminManager.GetByCondition(session, -1, adminName, null) != null)
                    throw new Exception("当前系统已存在这个用户，请换一个用户名。");
                admin = new Admin();
                admin.adminName = adminName;
                admin.adminPass = adminPass;
                admin.lastLoginIp = "";
                admin.lastLoginTime = DateTime.Now;
                admin.loginTimes = 0;
                AdminGroup adminGroup = AdminGroupManager.Get(session, adminGroupId);
                if (adminGroup == null)
                    throw new Exception("当前管理员所选择用户组已经被删除。");
                admin.adminGroup = adminGroup;
                AdminManager.Add(session, admin);

                CollisionManager.DeleteItem(session, collision);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        public static void AddAdmin1(string adminName, string adminPass, string adminGroupName)
        {
            ISession session = null;
            ITransaction trans = null;
            Admin admin = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                AdminGroup adminGroup = AdminGroupManager.GetByCondition(session, -1, adminGroupName, false, false);
                if (adminGroup == null)
                    throw new Exception("当前管理员所选择用户组已经被删除。");
                //冲突处理
                Collision collision = new Collision();
                collision.itemKey = "deleteAdminGroup_" + adminGroup.groupId.ToString();
                CollisionManager.AddItem(session, collision);

                if (AdminManager.GetByCondition(session, -1, adminName, null) != null)
                    throw new Exception("当前系统已存在这个用户，请换一个用户名。");
                admin = new Admin();
                admin.adminName = adminName;
                admin.adminPass = adminPass;
                admin.lastLoginIp = "";
                admin.lastLoginTime = DateTime.Now;
                admin.loginTimes = 0;
                admin.adminGroup = adminGroup;
                AdminManager.Add(session, admin);

                CollisionManager.DeleteItem(session, collision);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region 返回查询到Admin对象的result结果集
        /// <summary>
        /// 返回查询到VO.Admin对象的result结果集
        /// </summary>
        /// <param name="adminName">该项可以为null</param>
        /// <param name="rowIndex"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public static Result<Basic.VO.Admin> GetAllByCondition(string adminName,int adminGroupId, int rowIndex, int rowCount)
        {
            Result<Basic.VO.Admin> result = new Result<Basic.VO.Admin>();
            IList<Admin> entityData = new List<Admin>();
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                entityData = AdminManager.GetAllByCondition(session, adminName, null, adminGroupId, rowIndex, rowCount);
                result.total = AdminManager.GetAllByConditionCount(session, adminName, null, adminGroupId);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            result.data = new List<Basic.VO.Admin>();
            for (int i = 0; i < entityData.Count; i++)
            {
                Basic.VO.Admin admin = new Basic.VO.Admin();
                admin.adminId = entityData[i].adminId;
                admin.adminName = entityData[i].adminName;
                admin.lastLoginIp = entityData[i].lastLoginIp;
                admin.lastLoginTime = Tools.ToDateTimeString(entityData[i].lastLoginTime);
                admin.loginTimes = entityData[i].loginTimes;
                if (entityData[i].adminGroup != null)
                {
                    admin.adminGroup = new Basic.VO.AdminGroup();
                    admin.adminGroup.groupId = entityData[i].adminGroup.groupId;
                    admin.adminGroup.groupName = entityData[i].adminGroup.groupName;
                }
                result.data.Add(admin);
            }
            return result;
        }
        #endregion

        #region 根据用户名密码用户是否符合,符合则返回该Admin对象，不符合则返回null.
        /// <summary>
        /// 根据用户名密码用户是否符合,符合则返回该Admin对象，不符合则返回null.
        /// </summary>
        /// <param name="adminName"></param>
        /// <param name="adminPass"></param>
        /// <returns></returns>
        public static Basic.VO.Admin Get(string adminName, string adminPass)
        {
            ISession session = null;
            ITransaction trans = null;
            Basic.VO.Admin admin = null;
            Admin entityAdmin = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                entityAdmin = AdminManager.GetByCondition(session, -1, adminName, adminPass);
                if (entityAdmin != null)
                {
                    admin = new Basic.VO.Admin();
                    admin.adminId = entityAdmin.adminId;
                    admin.adminName = entityAdmin.adminName;
                    admin.lastLoginIp = entityAdmin.lastLoginIp;
                    admin.lastLoginTime = Tools.ToDateTimeString(entityAdmin.lastLoginTime);
                    admin.loginTimes = entityAdmin.loginTimes;
                    if (entityAdmin.adminGroup != null)
                    {
                        admin.adminGroup = new Basic.VO.AdminGroup();
                        admin.adminGroup.groupId = entityAdmin.adminGroup.groupId;
                        admin.adminGroup.groupName = entityAdmin.adminGroup.groupName;
                    }
                    if (entityAdmin.adminGroup.roles != null)
                    {
                        admin.adminGroup.roleNames = "拥有的权限为：";
                        IEnumerator<Role> entityRole = entityAdmin.adminGroup.roles.GetEnumerator();
                        while (entityRole.MoveNext())
                        {
                            admin.adminGroup.roleNames += entityRole.Current.roleName + ",";
                        }
                    }
                }
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            return admin;
        }
        #endregion


        #region 删除，根据adminId数组删除admin对象
        public static void DeleteAdmin(int[] adminIds)
        {
            ISession session = null;
            ITransaction trans = null;
            IList<Admin> list = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                list = AdminManager.GetAllByCondition(session, null, adminIds, -1, -1, -1);
                foreach (Admin admin in list)
                {
                    if (!admin.adminName.Equals("admin"))
                        AdminManager.Delete(session, admin);
                }
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region 更新一个Admin对象.
        /// <summary>
        /// 根据adminId更新admin对象
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="lastLoginIp"></param>
        /// <param name="lastLoginTime"></param>
        /// <param name="loginTimes"></param>
        public static void Update(int adminId, string lastLoginIp, DateTime lastLoginTime, int loginTimes)
        {
            ISession session = null;
            ITransaction trans = null;
            Admin admin = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                admin = AdminManager.Get(session, adminId);
                admin.lastLoginIp = lastLoginIp;
                admin.lastLoginTime = lastLoginTime;
                admin.loginTimes = loginTimes;
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        public static void Update(int adminId, string adminPass, int adminGroupId)
        {
            ISession session = null;
            ITransaction trans = null;
            Admin admin = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                admin = AdminManager.GetByCondition(session, adminId, null, null);
                if (admin.adminName.Equals("admin"))
                    throw new Exception("admin为系统默认留存账户，不允许其他人修改。");
                if (!String.IsNullOrEmpty(adminPass))
                    admin.adminPass = adminPass;
                admin.adminGroup = AdminGroupManager.Get(session, adminGroupId);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region 修改密码
        /// <summary>
        /// 根据adminId更改密码
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="adminPass"></param>
        /// <param name="newPassword"></param>
        public static void UpdatePassword(int adminId, string adminPass, string newPassword)
        {
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                Admin admin = AdminManager.GetByCondition(session, adminId, null, adminPass);
                if (admin == null)
                    throw new Exception(StringTable.ErrorOldPassWord);
                admin.adminPass = newPassword;
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion
    }
}
